package com.example.sup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sup.config.SupSchedulingConfigurerOptimize;
import com.example.sup.constans.UserInfoRoleEnum;
import com.example.sup.conttroller.response.ServerResponse;
import com.example.sup.entity.Prison;
import com.example.sup.entity.TaskManagement;
import com.example.sup.entity.UserInfo;
import com.example.sup.service.PrisonService;
import com.example.sup.service.TaskManagementService;
import com.example.sup.mapper.TaskManagementMapper;
import com.example.sup.utils.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mac
* @description 针对表【task_management】的数据库操作Service实现
* @createDate 2024-07-19 10:05:17
*/
@Service
public class TaskManagementServiceImpl extends ServiceImpl<TaskManagementMapper, TaskManagement>
    implements TaskManagementService{
    @Resource
    private SupSchedulingConfigurerOptimize supSchedulingConfigurerOptimize;
    @Resource
    private PrisonService prisonService;

    @Override
    public ServerResponse updateByTaskId(TaskManagement taskManagement,
                                         UserInfo userInfo) {
        // 检查传入的对象是否为null
        if(userInfo == null || prisonService == null || taskManagement == null){
            throw new RuntimeException("传入的对象不能为空");
        }
        //TODO 0、鉴权
        if(!userInfo.getRole().equals(UserInfoRoleEnum.ADMIN.getCode())){
            //查询该用户管理的监室列表
            QueryWrapper<Prison> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Prison::getUserInfoId,userInfo.getUserId());
            List<Prison> prisonList = prisonService.list(queryWrapper);
            //用户：104 114 115       更新："104,114".cantains("103")
            List<String> prisonIdList = Arrays.asList(taskManagement.getPrisonId().split(","));//更新监室id集合
            List<Integer> authPrisonIdList = prisonList.stream().map(prison -> prison.getPrisonId()).collect(Collectors.toList());//有权限更新的监室id集合

            if(!(prisonIdList.stream()
                    .allMatch(prisonId->authPrisonIdList.stream().anyMatch(authPrisonId->authPrisonId.equals(Integer.valueOf(prisonId)))))){
                throw new RuntimeException("该用户没有管理该监室");
            }
        }

        //TODO 1、更新数据库中定时任务记录
        //将执行时间 转为cron表达式
        taskManagement.setCron(StringUtil.containCron(taskManagement.getWeekData(), Time.valueOf(taskManagement.getTaskTime())));
        taskManagement.setUserInfoId(userInfo.getUserId());
        taskManagement.setUpdateBy(userInfo.getUserName());
        taskManagement.setUpdateTime(LocalDateTime.now());


        boolean result = this.updateById(taskManagement);//更新数据库
        if(result){
            //TODO 2、重新开启这个定时任务
            supSchedulingConfigurerOptimize.refresh(taskManagement);//更新定时任务
        }else{
            return ServerResponse.fail("更新失败");
        }
        return ServerResponse.success(null);
    }
}




